package com.yifeng.repo.controller.kafka.message.produce;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.clients.producer.RoundRobinPartitioner;
import org.apache.kafka.clients.producer.UniformStickyPartitioner;
import org.apache.kafka.clients.producer.internals.DefaultPartitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.utils.Utils;

import java.util.List;
import java.util.Map;

/**
 * Created by daibing on 2024/5/1.
 */
public class OrderPartitioner implements Partitioner {

    /**
     * 顺序分区选择器，参考轮询分区选择器
     * @see RoundRobinPartitioner#partition(String, Object, byte[], Object, byte[], Cluster)
     * @see DefaultPartitioner#partition(String, Object, byte[], Object, byte[], Cluster)
     * @see UniformStickyPartitioner#partition(String, Object, byte[], Object, byte[], Cluster)
     */
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        int nextValue = key.hashCode();
        List<PartitionInfo> availablePartitions = cluster.availablePartitionsForTopic(topic);
        if (!availablePartitions.isEmpty()) {
            int part = Utils.toPositive(nextValue) % availablePartitions.size();
            return availablePartitions.get(part).partition();
        } else {
            // no partitions are available, give a non-available partition
            List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
            return Utils.toPositive(nextValue) % partitions.size();
        }
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> configs) {

    }
}
